<?php

namespace App\Libraries;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;

class Gpt
{
    public function run($messages)
    {
        $endpoint = env('OPENAI_ENDPOINT');
        $apiKey = env('OPENAI_APIKEY');
        $modelName = env('OPENAI_MODEL');
        $apiVersion = env('OPENAI_VERSION');

        try {
            $uri = $endpoint . "/openai/deployments/" . $modelName . "/chat/completions?api-version=" . $apiVersion;
            $headers = [
                'Content-Type' => 'application/json',
                'api-key' => $apiKey
            ];
            // 请求参数
            $body = json_encode([
                "messages" => [
                    [
                        'role' => 'user',
                        'content' => $messages,
                    ]
                ],
            ], JSON_UNESCAPED_UNICODE);

            $client = new Client([
                'timeout'  => 120, // 设置请求超时时间为10秒
                'connect_timeout' => 10, // 设置连接超时时间为5秒
            ]);
            $response = $client->post($uri, [
                'headers' => $headers,
                'body' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }
            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException $e) {
            dd($e->getMessage());
        } catch (ConnectException $e) {
            dd($e->getMessage());
        }
    }
}
